#!/usr/bin/python3
# -*- coding:UTF-8 -*-
'''=================================
@Motto : 认真生活,热爱生活
@Name :       Bsea
================================='''
from flask import Blueprint, request, jsonify, session
from api import db
from .datebase import UserMessage, NoteIndex
import json

us = Blueprint('user', __name__, url_prefix='/')


# blog注册
@us.route('/register', methods=["POST"])
def register():
    message = request.get_json()
    username = message.get("username")
    password = message.get("password")
    if not all([username, password]):
        return jsonify({"code": "401", "msg": "参数不完成"})
    try:
        user = UserMessage(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return jsonify({"code": "200", "msg": {'text': "注册成功", 'username': username, 'password': password}})
    except:
        return jsonify({"code": "502", "msg": "注册失败"})


# blog登陆
@us.route('/login', methods=["POST"])
def login():
    message = request.get_json()
    username = message.get("username")
    password = message.get("password")
    if not all([username, password]):
        return jsonify({'code': "401", 'msg': '参数不全!'})
    try:
        blog_user = UserMessage.query.filter_by(username=username).first()
        if blog_user and blog_user.password == password:
            return jsonify({
                'code': "200",
                'msg': '登录成功!',
                'islogin': "true",
                'username': blog_user.username})
        else:
            return jsonify({'code': "201", 'msg': '账号或密码错误!'})
    except:
        return jsonify({'code': "202", 'msg': '登录失败!'})


# # blog检查登陆
# @us.route('/checklogin', methods=["GET"])
# def checklogin():
#     try:
#         username = session['username']
#         if username is not None:
#             return jsonify({"code": "500", "msg": {"username": username}})
#     except:
#         return jsonify({"code": "501", "msg": "你还未登陆!"})


# blog退出登陆
@us.route('/logout', methods=["GET"])
def logout():
    try:
        if session['username'] is not None:
            session.clear()
            return jsonify({"code": "600", "msg": "退出成功!"})
    except:
        return jsonify({"code": "601", "msg": "退出失败!"})


# note页
@us.route('/addnote', methods=["POST"])
def addnote():
    try:
        get_message = request.get_json()
        username = get_message['username']
        title = get_message['title']
        edittext = get_message["edittext"]
        date = get_message["date"]
        print(date)
        message = NoteIndex(username=username, date=date, title=title, text=edittext)
        db.session.add(message)
        db.session.commit()
        return jsonify({'code': "200", "msg": "编辑成功!"})
    except:
        return jsonify({'code': "201", "msg": "编辑失败!"})


# 获取笔记
def editnote(note):
    return {
        'id': note.id,
        'username': note.username,
        'date': note.date,
        'title': note.title,
        'text': note.text
    }


@us.route('/getnote', methods=["POST"])
def getnote():
    try:
        get_message = request.get_json()
        username = get_message['username']
        notelist = NoteIndex.query.filter_by(username=username).all()
        list = []
        for note in notelist:
            message = json.dumps(note, default=editnote)
            list.append(eval(message))
        print(list)
        return jsonify({'code': "200", "msg": list})
    except:
        return jsonify({'code': "201", "msg": "编辑失败!"})


# 删除笔记
@us.route('/deletenote', methods=["POST"])
def deletenote():
    try:
        get_message = request.get_json()
        id = get_message['id']
        date = get_message['date']
        username = get_message['username']
        print(id, date, username)
        if (id != -1):
            notelist = NoteIndex.query.filter_by(id=id, username=username).first()
            db.session.delete(notelist)
            db.session.commit()
        else:
            notelist = NoteIndex.query.filter_by(date=date, username=username).first()
            db.session.delete(notelist)
            db.session.commit()
        return jsonify({'code': "200", "msg": '删除成功!'})

    except:
        return jsonify({'code': "201", "msg": "编辑失败!"})
